package com.wandian.games.views;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import com.mylib.libcore.utils.UIUtils;
import com.wandian.games.R;
import com.wandian.games.bean.LotteryDataBean;

import java.util.ArrayList;
import java.util.List;

/**
 * create by cl 2020-05-18
 * 9宫格抽奖
 */
public class CusLuckyView extends View {
    private Paint mPaint;
    private float mStrokeWidth = 5;
    private int mRepeatCount = 5; // 转的圈数
//    private int mRectSize; // 矩形的宽和高（矩形为正方形）
    private int view_width; // 矩形的宽
    private int view_height; // 矩形的高
    private boolean mShouldStartFlag;
    private boolean mShouldStartNextTurn = true; // 标记是否应该开启下一轮抽奖
    private int mStartLuckPosition = 0; // 开始抽奖的位置
    private int mCurrentPosition = -1; // 当前转圈所在的位置
    private Canvas canvas;

    private OnLuckAnimationEndListener mLuckAnimationEndListener;

    private LotteryStart lotteryStart;

    /**
     * 可以通过对 mLuckNum 设置计算策略，来控制用户 中哪些奖 以及 中大奖 的概率
     */
    private int mLuckNum = 3; // 默认最终中奖位置

    private List<RectF> mRectFs; // 存储矩形的集合

    private int center_draw = R.drawable.img_lottery_start;

//    private String[] mPrizeDescription = {"满20减1元券", "满10减1元券", "满30减2元券", "满5减1元券", "免单", "满300减40元券", "满100减10元券", "满500减50元券", "开始"};
    private int[] mLuckyPrizes = {R.drawable.img_lettory_icon_1, R.drawable.img_lettory_icon_2, R.drawable.img_lettory_icon_3, R.drawable
            .img_lettory_icon_4,  R.drawable.img_lettory_icon_5,R.drawable.img_lettory_icon_6, R.drawable.img_lettory_icon_7,
        R.drawable.img_lettory_icon_8, R.drawable.img_lettory_icon_5};

    private List<String> listBean  = new ArrayList<>();

    private float left;
    private float top;
    private Bitmap[] bitmaps;
    private String[] luckyName;
    private String[] id;
    private int selectPos;


    public CusLuckyView(Context context) {
        this(context, null);
    }

    public CusLuckyView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CusLuckyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        listBean.clear();
        for(int i=0;i<9;i++){
            listBean.add("1金币");
        }
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // 抗锯齿
        mPaint.setStyle(Paint.Style.FILL);
        // mPaint.setStyle(Paint.Style.STROKE); // 设置样式为描边
        mPaint.setStrokeWidth(mStrokeWidth); // 设置描边的宽度

        mRectFs = new ArrayList<>();
    }

    public void initLuckyView(List<String> listBean){
        if(UIUtils.isEmpty(listBean)){
            return;
        }else {
            this.listBean =listBean;
      //     mPrizeDescription = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "开始"};
            invalidate();
        }
    }

    public void setLuckAnimationEndListener(OnLuckAnimationEndListener luckAnimationEndListener) {
        mLuckAnimationEndListener = luckAnimationEndListener;
    }
    public void setLotteryStartListener(LotteryStart lotteryStart) {
        this.lotteryStart = lotteryStart;
    }

    public int getLuckNum() {
        return mLuckNum;
    }

    public void setLuckNum(int luckNum) {
        mLuckNum = luckNum;
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 矩形的宽高
        view_width = w/3;
        view_height = h/3;
     //   mRectSize = (Math.min(w, h)) / 3;
        // 当控件大小改变的时候清空数据
        mRectFs.clear();
        initNineRect();
    }

//    /**
//     * 初始化 9 个矩形（正方形）的位置信息
//     */
//    private void initNineRect(int width) {
//        final float spec = (getWidth()-width)/2;
//
//        // 加载前三个矩形
//        for (int i = 0; i < 3; i++) {
//            float left = i * mRectSize + 5+spec;
//            float right = (i + 1) * mRectSize+spec;
//            float top = 5;
//            float bottom = mRectSize;
//            RectF rectF = new RectF(left, top, right, bottom);
//            mRectFs.add(rectF);
//        }
//
//        // 加载第 4 个矩形
//        mRectFs.add(new RectF(width - mRectSize + 5+spec, mRectSize + 5, width+spec, 2 * mRectSize));
//
//        // 加载第 5~7 个矩形
//        for (int j = 3; j > 0; j--) {
//            float left = width - (4 - j) * mRectSize + 5+spec;
//            float right = width - (3 - j) * mRectSize+spec;
//            float top = 2 * mRectSize + 5;
//            float bottom = 3 * mRectSize;
//            RectF rectF = new RectF(left, top, right, bottom);
//            mRectFs.add(rectF);
//        }
//
//        // 加载第 8 个矩形
//        mRectFs.add(new RectF(5+spec, mRectSize + 5, mRectSize+spec, 2 * mRectSize));
//
//        // 加载中心第 9 个矩形
//        mRectFs.add(new RectF(mRectSize + 5+spec, mRectSize + 5, 2 * mRectSize+spec, 2 * mRectSize));
//    }

    /**
     * 初始化 9 个矩形（正方形）的位置信息
     */
    private void initNineRect() {
        final float width = getWidth();

        // 加载前三个矩形
        for (int i = 0; i < 3; i++) {
            float left = i * view_width + 5;
            float right = (i + 1) * view_width;
            float top = 5;
            float bottom = view_height;
            RectF rectF = new RectF(left, top, right, bottom);
            mRectFs.add(rectF);
        }

        // 加载第 4 个矩形
        mRectFs.add(new RectF(width - view_width + 5, view_height + 5, width, 2 * view_height));

        // 加载第 5~7 个矩形
        for (int j = 3; j > 0; j--) {
            float left = width - (4 - j) * view_width + 5;
            float right = width - (3 - j) * view_width;
            float top = 2 * view_height + 5;
            float bottom = 3 * view_height;
            RectF rectF = new RectF(left, top, right, bottom);
            mRectFs.add(rectF);
        }

        // 加载第 8 个矩形
        mRectFs.add(new RectF(5, view_height + 5, view_width, 2 * view_height));

        // 加载中心第 9 个矩形
        mRectFs.add(new RectF(view_width + 5, view_height + 5, 2 * view_width, 2 * view_height));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        this.canvas =canvas;

        //执行真正的绘制矩形操作
        drawNineRect(canvas);
        // 填充奖品图片
        drawNineBitmaps(canvas);
        // 填充奖品文字
        drawNineText(canvas);
    }

    /**
     * 在每个矩形中填充奖品图片
     * left：The position of the left side of the bitmap being drawn
     * top：The position of the top side of the bitmap being drawn
     */
    private void drawNineBitmaps(final Canvas canvas) {

        for (int i = 0; i < mRectFs.size(); i++) {
            RectF rectF = mRectFs.get(i);
            // 将图片设置在每个矩形中央
            left = rectF.left + view_width / 4;
            top = rectF.top + view_height / 8;
            if(listBean.size()>i){
                if(i>=8){
                 //   canvas.drawBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.img_cj_6), mRectSize / 2, mRectSize / 2, false), left, top, null);
                    return;
                }else {
                    canvas.drawBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(),mLuckyPrizes[i]), view_width / 2, view_height / 2, false), left, top, null);
                }
            }else {
                canvas.drawBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), mLuckyPrizes[0]), view_width / 2, view_height / 2, false), left, top, null);
            }

        }
    }


    /**
     * 在每个矩形中央填充文字，代替抽奖图片
     * x：he x-coordinate of the origin of the text being drawn
     * y：The y-coordinate of the baseline of the text being drawn
     */
    private void drawNineText(Canvas canvas) {
        for (int i = 0; i < mRectFs.size(); i++) {
            RectF rectF = mRectFs.get(i);
            float x = rectF.left + view_width / 4; // 将文字设置在每个矩形中央
            float y = rectF.top + view_height - 30;
            mPaint.setColor(Color.parseColor("#5e5448"));
            mPaint.setStyle(Paint.Style.FILL);
            mPaint.setTextSize(20); // unit px
            if (i == mRectFs.size() - 1) {
                canvas.drawText("", x, y, mPaint);
            } else {
                if(listBean.size()>i){
                    if(!UIUtils.isEmpty(listBean.get(i).toString())){
//                        Paint pFont = new Paint();
//                        mPaint.setTextSize(20); // unit px
//                        Rect rect = new Rect();
//                        pFont.getTextBounds(listBean.get(i).getTitle()+"", 0, listBean.get(i).getTitle().length(), rect);

                        Paint pFont = new Paint();
                        pFont.setTextSize(20); //
                        Rect rect = new Rect();
                    //返回包围整个字符串的最小的一个Rect区域
                        pFont.getTextBounds(listBean.get(i).toString()+"", 0, (listBean.get(i).toString()+"").length(), rect);
                        Log.d("listBeantext",rect.width()+"="+view_width);
                        x =  rectF.left+((view_width-rect.width())/2);
                        canvas.drawText(listBean.get(i).toString()+"", x, y, mPaint);
                    }else {
                        canvas.drawText("", x, y, mPaint);
                    }
                }else {
                    canvas.drawText("", x, y, mPaint);
                }
            }
        }
    }

    /**
     * 执行真正的绘制矩形操作
     */
    private void drawNineRect(Canvas canvas) {
        for (int x = 0; x < mRectFs.size(); x++) {
            RectF rectF = mRectFs.get(x);
            if (x == 8) {
                //mPaint.setColor(Color.WHITE);
                //  mPaint.setColor(Color.parseColor("#edcea9"));
                Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(),center_draw);
                //绘制方法2：--先裁剪再展示
                canvas.drawBitmap(bitmap,null,rectF, mPaint);
            } else {
                if (mCurrentPosition == x) {
                  //  mPaint.setColor(Color.parseColor("#edcea9"));
                    Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.img_lettory_red);
                    //绘制方法2：--先裁剪再展示
                    canvas.drawBitmap(bitmap,null,rectF, mPaint);
                } else {
               //     mPaint.setColor(mItemColor[x % 2]); // 标记当前转盘经过的位置
                    Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.img_lettory_white);
                    //绘制方法2：--先裁剪再展示
                    canvas.drawBitmap(bitmap,null,rectF, mPaint);
                }
            }
          //  canvas.drawRect(rectF, mPaint);


        }
    }

    /**
     * 绘制倒计时
     * @return
     */
    public void drawDJSRect() {
        Log.d("drawDJSRect","drawDJSRect");
        center_draw = R.drawable.img_lottery_start_djs;
        invalidate();
    }

    /**
     * 绘制倒计时
     * @return
     */
    public void drawLotteryRect() {
        center_draw = R.drawable.img_lottery_start;
        invalidate();
    }



    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            mShouldStartFlag = mRectFs.get(8).contains(event.getX(), event.getY());
            return true;
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (mShouldStartFlag) {
                if (mRectFs.get(8).contains(event.getX(), event.getY())) {
                    lotteryStart.setOnLotteryStart();
                    // mLuckAnimationEndListener.onClickLuck();
//                    startAnim(1); // 判断只有手指落下和抬起都在中间的矩形内时才开始执行动画抽奖
                }
                mShouldStartFlag = false;
            }
        }
        return super.onTouchEvent(event);
    }

    /**
     * 开始动画
     * @param
     */
    public void startAnim() {
        if (!mShouldStartNextTurn) {
            return;
        }



        ValueAnimator animator = ValueAnimator.ofInt(mStartLuckPosition, mRepeatCount * 8 + mLuckNum).setDuration(5000);

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                final int position = (int) animation.getAnimatedValue();
                setCurrentPosition(position % 8);
                mShouldStartNextTurn = false;
            }
        });

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mShouldStartNextTurn = true;
                mStartLuckPosition = mLuckNum;
                //最终选中的位置
                if (mLuckAnimationEndListener != null) {
                    if(mCurrentPosition<listBean.size()){
                        mLuckAnimationEndListener.onLuckAnimationEnd(mCurrentPosition, listBean.get(mCurrentPosition).toString()+"");
                    }
                }
            }
        });

        animator.start();
    }

    private void setCurrentPosition(int position) {
        mCurrentPosition = position;
        invalidate(); // 强制刷新，在 UI 线程回调 onDraw()
    }

    public void setBitmap(Bitmap[] bitmaps1, String[] name, String[] strings) {
        bitmaps = bitmaps1;
        luckyName = name;
        id = strings;
        invalidate();
    }

    /**
     * 选中id
     *
     * @param datas
     */
    public void setSelectId(int datas) {
        String selectId = datas + "";

        if (id != null && id.length != 0) {
            for (int i = 0; i < id.length; i++) {
                if (id[i].equals(selectId)) {
                    selectPos = i;
                }
            }
        }
        startAnim();
    }

    /**
     * 用于抽奖结果回调
     */
    public interface OnLuckAnimationEndListener {
        void onLuckAnimationEnd(int pos, String msg);
    }
    /**
     * 用于抽奖结果回调
     */
    public interface LotteryStart {
        void setOnLotteryStart();
    }
}

